﻿using System;
using System.Collections.Generic;
using System.Linq;

using SharedGenomics.Core;

namespace SharedGenomics.Domain.Builders
{
    public class DataSetInfoBuilder : IBuilder<DataSetInfo>
    {
        private int? _fileSetId;
        private string _name;
        private FilterParameterSetInfo _parameters;

        public DataSetInfoBuilder ForFileSet(int fileSetId)
        {
            this._fileSetId = fileSetId;
            return this;
        }

        public DataSetInfoBuilder Called(string name)
        {
            this._name = name;
            return this;
        }

        public DataSetInfoBuilder WithParameters(FilterParameterSetInfo parameterSet)
        {
            this._parameters = parameterSet;
            return this;
        }

        public DataSetInfo Build()
        {
            var validationErrors = this.Validate();
            ExceptionHelper.ThrowIf<BuilderStateException>(!validationErrors.IsValid, "Builder state invalid");

            return new DataSetInfo
            {
                FileSetId = this._fileSetId.Value,
                Name = this._name,
                Parameters = this._parameters
            };
        }

        public PropertyValidationErrorCollection Validate()
        {
            PropertyValidationErrorCollection errors = new PropertyValidationErrorCollection();
            this.AddPropertyErrorIfNull(this._fileSetId, errors, "FileSetId", "File set id required");
            this.AddPropertyErrorIfNull(this._name, errors, "Name", "Name required");
            this.AddPropertyErrorIfNull(this._parameters, errors, "Parameters", "Parameters required");

            return errors;
        }

        private void AddPropertyErrorIfNull(object value, PropertyValidationErrorCollection errors, string propertyName, string error)
        {
            if (value == null)
            {
                errors.AddError(propertyName, error);
            }
        }

        private string GetBuilderStateMessage(string missingPropertyName)
        {
            return String.Format("Cannot create DataSetInfo - {0} not given", missingPropertyName);
        }
    }
}
